package command;

import model.FarmMachine;

/**
 * 启动设备命令
 */
public class StartCommand implements Command {
    private final AgriculturalDevice device;
    private boolean wasRunning = false; // 记录执行前的状态

    public StartCommand(AgriculturalDevice device) {
        this.device = device;
    }


    @Override
    public void execute() {
        wasRunning = device.isRunning();
        if (!wasRunning) {
            System.out.println("启动设备: " + device.getDeviceId());
            device.start();
            if (device instanceof FarmMachine) {
                FarmMachine farmMachine = (FarmMachine) device;
                farmMachine.getStateContext().request(); // 触发状态转换
            }
        } else {
            System.out.println("设备已在运行中: " + device.getDeviceId());
        }
    }

    @Override
    public void undo() {
        if (!wasRunning) { // 如果执行前设备未运行，则撤销时停止设备
            System.out.println("撤销启动: " + device.getDeviceId());
            device.stop();
            if (device instanceof FarmMachine) {
                FarmMachine farmMachine = (FarmMachine) device;
                farmMachine.getStateContext().setState(new state.IdleState()); // 设置为待机状态
            }
        }
    }
}
